package com.ecy.quadratic.ui.activity;

import android.content.Intent;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.ecy.quadratic.R;
import com.ecy.quadratic.adapter.PostCommunityAdapter;
import com.ecy.quadratic.adapter.PostSpecialAreaAdapter;
import com.ecy.quadratic.beans.CommunitySpecialArea;
import com.ecy.quadratic.beans.user.User;
import com.ecy.quadratic.component.DaggerCommunityMainComponent;
import com.ecy.quadratic.manager.EventManager;
import com.ecy.quadratic.manager.LoginManager;
import com.ecy.quadratic.photopicker.PhotoPicker;
import com.ecy.quadratic.photopicker.PhotoPreview;
import com.ecy.quadratic.photopicker.RecyclerItemClickListener;
import com.ecy.quadratic.reader.base.BaseActivity;
import com.ecy.quadratic.reader.component.AppComponent;
import com.ecy.quadratic.reader.utils.ToastUtils;
import com.ecy.quadratic.ui.contract.PostCommunityContract;
import com.ecy.quadratic.ui.presenter.PostCommunityPresenter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;


public class PostCommunityActivity extends BaseActivity implements PostCommunityContract.View {

    @Bind(R.id.et_community_content)
    EditText mEtPostCommunity;
    @Bind(R.id.community_specialarea_listview)
    ListView mLvSpecialArea;

    @Inject
    PostCommunityPresenter mPresenter;

    private PostCommunityAdapter photoAdapter;

    private PostSpecialAreaAdapter specialAreaAdapter;

    private ArrayList<String> selectedPhotos = new ArrayList<>();

    private List<CommunitySpecialArea> mNovelList;
    private Map<String, String> map = new HashMap<String, String>();

    @Override
    public int getLayoutId() {
        return R.layout.photopicker_activity_main;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerCommunityMainComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void initToolBar() {

    }

    @Override
    public void initData() {
        mNovelList = new ArrayList<CommunitySpecialArea>();
        CommunitySpecialArea area = new CommunitySpecialArea();
        area.setId("cp");
        area.setTitle("CP交友");
        area.setDes("求眼熟，求搅基，求CP!");
        area.setImgResId(R.drawable.special_cp);
        area.setBackgroundColor(0xffdbfedd);
        area.setImg("http://img0.u17i.com/10/06/4240/wp/5131_1276619192_FzzJwPW0DX2f.3a006_50.jpg");
        mNovelList.add(area);
        CommunitySpecialArea area2 = new CommunitySpecialArea();
        area2.setId("comic");
        area2.setTitle("漫画");
        area2.setDes("授权漫画有100元奖励!");
        area2.setImgResId(R.drawable.special_comic);
        area2.setBackgroundColor(0xfffcdeeb);
        area2.setImg("http://img2.imgtn.bdimg.com/it/u=812138972,3998046532&fm=23&gp=0.jpg");
        mNovelList.add(area2);
        CommunitySpecialArea area3 = new CommunitySpecialArea();
        area3.setId("cos");
        area3.setTitle("COS");
        area3.setImgResId(R.drawable.special_cos);
        area3.setDes("欢迎COSPLAY同好，打破次元墙~!!!");
        area3.setBackgroundColor(0xffe9defc);
        area3.setImg("http://img3.imgtn.bdimg.com/it/u=515765522,418236175&fm=23&gp=0.jpg");
        mNovelList.add(area3);
        CommunitySpecialArea area4 = new CommunitySpecialArea();
        area4.setId("beauty");
        area4.setTitle("动漫美图");
        area4.setImgResId(R.drawable.special_beauty);
        area4.setDes("做优秀美图搬运工，搬砖啦上路啦");
        area4.setBackgroundColor(0xffdefcfc);
        area4.setImg("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3708147988,4053567601&fm=11&gp=0.jpg");
        mNovelList.add(area4);
        CommunitySpecialArea area5 = new CommunitySpecialArea();
        area5.setId("share");
        area5.setTitle("资源共享");
        area5.setImgResId(R.drawable.special_share);
        area5.setDes("不要污，不要啊，不要啊...");
        area5.setBackgroundColor(0xfff0f8f8);
        area5.setImg("http://img0.imgtn.bdimg.com/it/u=588688756,37876964&fm=23&gp=0.jpg");
        mNovelList.add(area5);
        CommunitySpecialArea area6 = new CommunitySpecialArea();
        area6.setId("common");
        area6.setTitle("日常");
        area6.setDes("少年少女们，快来啊快来啊");
        area6.setBackgroundColor(0xfff1f4ef);
        area6.setImgResId(R.drawable.special_daily);
        area6.setImg("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496379801222&di=aa8aaa4538a835fbc736dd65435c24c9&imgtype=0&src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F17%2F94%2F09%2F76b58PICr5M_1024.jpg");
        mNovelList.add(area6);
    }

    @Override
    public void configViews() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        photoAdapter = new PostCommunityAdapter(this, selectedPhotos);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(photoAdapter);

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (photoAdapter.getItemViewType(position) == PostCommunityAdapter.TYPE_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(PostCommunityAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(true)
                                    .setSelected(selectedPhotos)
                                    .start(PostCommunityActivity.this);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(PostCommunityActivity.this);
                        }
                    }
                }));
        specialAreaAdapter = new PostSpecialAreaAdapter(this, mNovelList);
        mLvSpecialArea.setAdapter(specialAreaAdapter);
        mLvSpecialArea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (specialAreaAdapter.getSelectedMap().containsKey(mNovelList.get(position).getId())) {
                    specialAreaAdapter.getSelectedMap().remove(mNovelList.get(position).getId());
                } else {
                    specialAreaAdapter.getSelectedMap().put(mNovelList.get(position).getId(), mNovelList.get(position).getTitle());
                }
                specialAreaAdapter.notifyDataSetChanged();
            }
        });
        mPresenter.attachView(this);

    }

    @OnClick(R.id.tv_post_community_cancel)
    public void cancel() {
        finish();
    }

    @OnClick(R.id.tv_send)
    public void send() {
        User user = LoginManager.getInstance().getUser();
        Map<String, String> params = new HashMap<>();
        params.put("content", mEtPostCommunity.getText().toString());
        params.put("user", LoginManager.getInstance().getUserJson());
        if (!TextUtils.isEmpty(user.userId)) {
            params.put("userid", user.userId);
        }
        Collection<String> tagList = specialAreaAdapter.getSelectedMap().values();
        if (tagList != null) {
            String tags = new Gson().toJson(tagList, Collection.class);
            if (!TextUtils.isEmpty(tags)) {
                params.put("tags", tags);
            }
        }

        mPresenter.postCommunity(params, selectedPhotos);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {

                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showError() {
        ToastUtils.getSingleToast("发表失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void complete() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    @Override
    public void onPostSuccess() {
        EventManager.refreshCommunity();
        ToastUtils.getSingleToast("发表成功", Toast.LENGTH_SHORT).show();
        finish();
    }
}
